package test.mkk;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.util.Log;



public class AudioStreamer extends Thread{
	
	File file = new File(AudioPreferences.FILE_DIRECTORY, AudioPreferences.FILE_NAME);

	public AudioStreamer() { 
		android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
		start();
    }
	
	@Override
	public void run(){
		try {
			Thread.sleep(AudioPreferences.DELAY_TIME);
		} catch (InterruptedException e) {
			Log.d("STREAMER", "ERROR:", e);
		}
		
		int audioBufferSize = AudioRecord.getMinBufferSize(
        		AudioPreferences.FREQUENCY, 
        		AudioPreferences.CHANNEL_CONFIG,
        		AudioPreferences.AUDIO_ENCODING);
		
		Log.d("AudioBufferSize", ""+audioBufferSize);
		
		byte[] audioBuffer = new byte[audioBufferSize];
		try {
		  InputStream is = new FileInputStream(file);
		  AudioTrack audioTrack = new AudioTrack(
				  AudioManager.STREAM_MUSIC, 
		          AudioPreferences.FREQUENCY,
		          AudioPreferences.CHANNEL_CONFIG,
		          AudioPreferences.AUDIO_ENCODING, 
		          audioBufferSize, 
		          AudioTrack.MODE_STREAM);
		  audioTrack.play();  
		  int numberOfReadByte = 0;
		  audioTrack.write(audioBuffer, 0, audioBufferSize);

		  while (numberOfReadByte<file.length()) {
			  Log.d("STREAMER", String.valueOf(file.length()));
			  int result = is.read(audioBuffer, 0, audioBufferSize);
			  audioTrack.write(audioBuffer, 0, result);
			  numberOfReadByte+= result;
		  }
		} catch (Throwable t) {Log.d("STREAMER", "ERROR: ", t);}
	}
}
